package cn.wolfcode.controller;


import cn.wolfcode.annotation.BrushProof;
import cn.wolfcode.entity.Userinfo;
import cn.wolfcode.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.redis.service.IUserInfoRedisService;
import cn.wolfcode.redis.util.RedisKeys;
import cn.wolfcode.service.IUserinfoService;
import cn.wolfcode.util.JSONResult;
import cn.wolfcode.util.RequestUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author c1eye
 * @since 2022-11-03
 */
@RestController
@CrossOrigin
@RequestMapping("/users")
public class UserinfoController {
    @Autowired
    private IUserinfoService userinfoService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    /**
     * 检查手机号是否注册
     *
     * @param phone
     * @return
     */
    @GetMapping("/checkPhone")
    public boolean checkPhone(String phone) {
        return userinfoService.checkPhone(phone);
    }

    /**
     * 发送验证码
     *
     * @param phone
     */
    @GetMapping("/sendVerifyCode")
    @BrushProof(count = 20, time = 1, timeUnit = TimeUnit.MINUTES)
    public JSONResult sendVerifyCode(String phone) {
        userinfoService.sendVerifyCode(phone);
        return JSONResult.success();
    }

    /**
     * 注册用户
     *
     * @return
     */
    @PostMapping("/regist")
    public JSONResult regist(String phone, String nickname, String password, String rpassword, String verifyCode, HttpServletRequest request) {
        String uri = request.getRequestURI().substring(1);
        // ip最好转换成数字，这个现在是一堆冒号
        String ip = String.valueOf(RequestUtil.getIPAddress().replace(":", "."));
        String key = RedisKeys.BRUSH_PROOF.join(uri, ip);
        userinfoService.regist(phone, nickname, password, rpassword, verifyCode,key);
        return JSONResult.success();
    }

    @PostMapping("/login")
    public JSONResult login(String username, String password) {
        Userinfo user = userinfoService.login(username, password);
        String token = userInfoRedisService.setToken(user);
        user.setPassword("");
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", user);
        return JSONResult.success(map);
    }

    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    @GetMapping("strategies/favor")
    public JSONResult favor(Long sid, Long userId) {
        boolean favor = strategyStatisVORedisService.hasFavor(sid, userId);
        return JSONResult.success(favor);
    }
}

